package com.smart.seckilldemo.rocketmq.consumer;
import java.math.BigDecimal;
import java.util.Date;

import com.smart.seckilldemo.commons.dto.GenerateSeckillOrder;
import com.smart.seckilldemo.commons.vo.SeckillGoodsVo;
import com.smart.seckilldemo.mapper.OrderMapper;
import com.smart.seckilldemo.mapper.SeckillOrderMapper;
import com.smart.seckilldemo.pojo.Order;
import com.smart.seckilldemo.pojo.SeckillOrder;
import com.smart.seckilldemo.service.SeckillGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;



/**
 * 消费者服务 接收消息
 * 接收订单下单操作 生成订单锁定库存返回结果通知客户
 */
@Component
@Slf4j
@RocketMQMessageListener(topic = "tp_topic_1",consumerGroup = "consumer_grp_01")
public class RocketMQConsumer implements RocketMQListener<GenerateSeckillOrder> {

    @Resource
    RocketMQTemplate rocketMQTemplate;
    @Resource
    OrderMapper orderMapper;
    @Resource
    SeckillOrderMapper seckillOrderMapper;
    @Resource
    SeckillGoodsService seckillGoodsService;


    final String destinationTopic = "tp_topic_2";

    @Override
    public void onMessage(GenerateSeckillOrder msg) {
        Long userId = msg.getUserId();
        Long goodsId = msg.getGoodsId();
        Long orderId = msg.getOrderId();
        log.info("接收到消息 开始创建订单 ");
        //接收到请求订单生产
        //数据库锁定库存 减库存 分布式锁一致性 成功下单返回true
        //获取商品信息
        SeckillGoodsVo seckillGoodsVo = seckillGoodsService.finSeckillGoodByGoods(goodsId);
        //生成订单
        Order order = new Order();
        order.setUserId(userId);
        order.setOrderNumber(orderId);
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        order.setOrderStatus((byte)1);
        order.setAddress(0);
        order.setMoney(seckillGoodsVo.getSeckillPrice());
        order.setTypeId((byte)0);
        order.setHaha("我也不知到这个是啥");
        int insert = orderMapper.insert(order);
        if (insert==1){
            log.info("生成订单");
        }
        //生成秒杀订单
        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setUserId(userId);
        seckillOrder.setOrderId(orderId);
        seckillOrder.setGoodsId(goodsId);
        int insert1 = seckillOrderMapper.insert(seckillOrder);
        if(insert1==1){
            log.info("生成秒杀记录表");
        }
        //这边再次发送延迟消息
      rocketMQTemplate.syncSend(destinationTopic, MessageBuilder.withPayload(msg).build(),2000,2);

    }


}
